package com.bandi.tharshesnows;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.bandi.tharshesnows.model.County;
import com.bandi.tharshesnows.model.Resort;
import com.bandi.tharshesnows.model.Skirun;
import com.bandi.tharshesnows.service.SkirunsManager;

@SuppressLint("NewApi") public class LocalitiesActivity extends BaseActivity {

  protected static final String TAG = "SNOW";
  private ListView listView;
  private TextView textView;
  private LayoutInflater inflater;
  private SkirunsProvider provider;
  private County county;
  private boolean dataLoaded = false;
  private long countyId;
  private float deviceScreenDensity;
  private int deviceHeight;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.localities_activity);
    DisplayMetrics outMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
    deviceScreenDensity = outMetrics.density;
    deviceHeight = outMetrics.heightPixels;
    textView = (TextView) findViewById(R.id.county_text);
    listView = (ListView) findViewById(R.id.localities_list);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    inflater = LayoutInflater.from(this);
    provider = SkirunsProvider.getInstance();
    countyId = getIntent().getLongExtra("CountyID", 0);
  }

  @Override
  protected void onResume() {
    super.onResume();
    if (!dataLoaded) {
      provider.getCounty(countyId, new GetDataCallback<County>() {

        @Override
        public void onError(Throwable t) {
          Log.e(TAG, "get county failed.", t);
        }

        @Override
        public void onData(County data) {
          county = data;
          dataLoaded = true;
          refreshList();
        }
      });
    }
    else {
      refreshList();
    }
  }

  private void refreshList() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        textView.setText("Judetul " + county.getName());
        listView.setAdapter(new LocalitiesAdapter());
      }
    });
  }

  private class LocalitiesAdapter extends BaseAdapter {

    @Override
    public int getCount() {
      return county.getResorts().size();
    }

    @Override
    public Object getItem(int arg0) {
      return county.getResorts().get(arg0);
    }

    @Override
    public long getItemId(int position) {
      return county.getResorts().get(position).get_id();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if (convertView == null) {
        convertView = inflater.inflate(R.layout.locality_layout, null);
        convertView.setTag(new LocalityViewWrapper(convertView));
      }
      LocalityViewWrapper wrapper = (LocalityViewWrapper) convertView.getTag();
      wrapper.refresh(position);
      return convertView;
    }

  }

  private Set<Integer> expandedIndexes = new HashSet<Integer>();

  private class LocalityViewWrapper {
    TextView localityName;
    ImageView expandBtn;
    RelativeLayout expandLayout;
    LinearLayout skirunsLayout;
    ImageView localityOpenImageView;
    View rootView;
    private boolean expanded = false;
    int skirunslayoutHeight;
    private static final int SKIRUN_LAYOUT_HEIGHT_DIP = 54;

    public LocalityViewWrapper(View rootView) {
      this.rootView = rootView;
      localityName = (TextView) rootView.findViewById(R.id.locality_name);
      expandBtn = (ImageView) rootView.findViewById(R.id.expand_btn);
      expandLayout = (RelativeLayout) rootView.findViewById(R.id.expand_layout);
      skirunsLayout = (LinearLayout) rootView.findViewById(R.id.skiruns_layout);
      localityOpenImageView = (ImageView) rootView.findViewById(R.id.locality_open_img);
    }

    private void setExpanded(boolean expanded, int position) {
      this.expanded = expanded;
      expandBtn.setBackgroundResource(expanded ? R.drawable.expander_ic_maximized : R.drawable.expander_ic_minimized);
      skirunsLayout.setVisibility(expanded ? View.VISIBLE : View.GONE);
      if (expanded) {
        expandedIndexes.add(position);
        //listView.smoothScrollToPosition(position);
        //listView.smoothScrollByOffset(skirunslayoutHeight);
      }
      else {
        expandedIndexes.remove(position);
      }
    }

    public void refresh(final int position) {
      final Resort locality = county.getResorts().get(position);
      localityName.setText(locality.getName());
      skirunsLayout.removeAllViews();
      setExpanded(expandedIndexes.contains(position), position);
      boolean localityOpen = false;
      for (final Skirun skirun : locality.getSkiruns()) {
        View skirunView = inflater.inflate(R.layout.skirun_item_layout, null);
        TextView skirunName = (TextView) skirunView.findViewById(R.id.skirun_name);
        ImageView skirunStatus = (ImageView) skirunView.findViewById(R.id.skirun_open_img);
        ImageView skirunSaved = (ImageView) skirunView.findViewById(R.id.skirun_stored_img);
        skirunSaved.setVisibility(skirun.isDownloaded() ? View.VISIBLE : View.GONE);
        skirunStatus.setBackgroundResource(skirun.isOpen() ? R.drawable.skirun_open_list_item
            : R.drawable.skirun_closed_list_item);
        if (skirun.isOpen()) {
          localityOpen = true;
        }
        skirunName.setText(skirun.getName());
        skirunsLayout.addView(skirunView);
        skirunView.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {
            if (!isOnline() && !skirun.isDownloaded()) {
              showFailedAlert("Nu exista o conexiune la internet!");
              return;
            }
            Intent intent = new Intent(LocalitiesActivity.this, SkirunActivity.class);
            intent.putExtra("SKIRUN_ID", skirun.get_id());
            intent.putExtra("LOC_ID", locality.get_id());
            intent.putExtra("COUNTY_ID", locality.getCounty().get_id());
            startActivity(intent);
          }
        });
      }
      skirunslayoutHeight = (int) (locality.getSkiruns().size() * SKIRUN_LAYOUT_HEIGHT_DIP * deviceScreenDensity)+SKIRUN_LAYOUT_HEIGHT_DIP;
      localityOpenImageView.setBackgroundResource(localityOpen ? R.drawable.skirun_open_list_item
          : R.drawable.skirun_closed_list_item);
      expandLayout.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          setExpanded(!expanded, position);
        }
      });
    }
  }

}
